import json
import random
import re

from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from user import userser
from user.models import UserModel
from utils.authorization import MyAuthentication
from .tasks import add, send
from utils.jwttool import tooljwt
from utils.myredis import redistoll
from utils.sendmsg import send_message


# Create your views here.

class Loginpwd(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')

        info = UserModel.objects.filter(Q(username=account) | Q(email=account) | Q(phone=account)).first()
        if info is None:
            return Response({'code': 400, 'msg': '账号不存在'})
        elif info.password == password:
            data = {
                'id': info.id,
                'account': account,
                'token': tooljwt.getToken(info.id, account)
            }
            if info.head_img:
                data['head_img'] = info.head_img
            else:
                data['head_img'] = '/uploads/img/坤坤1.png'
            return Response({'code': 200, 'msg': '登录成功', 'data': data})
        else:
            return Response({'code': 400, 'msg': '密码错误'})


class SendCode(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = str(random.randint(1000, 9999))
        rediscode = redistoll.get_str(phone)
        if rediscode:
            return Response({'code':400,'msg':'请勿重复发送'})
        else:
            send.delay(phone,code)
            redistoll.set_str(phone,code,60*2)
            return Response({'code':200,'msg':'发送成功'})


class Login(APIView):
    def post(self, request):
        account = request.data.get('account')
        code = request.data.get('code')
        redis_code = redistoll.get_str(account)
        print(code, redis_code)

        if code != redis_code:
            return Response({'redis_code': redis_code, 'code': code})
        info = UserModel.objects.filter(phone=account, is_show=True).first()
        if info is None:
            new_data = UserModel.objects.create(phone=account)
            token = tooljwt.getToken(new_data.id, new_data.phone)
            id = new_data.id
            return Response(
                {'code': 200, 'message': '登录成功', 'data': {'token': token, 'id': id, 'account': account}}
            )
        token = tooljwt.getToken(info.id, info.phone)
        id = info.id
        return Response({'code': 200, 'message': '登录成功', 'data': {'token': token, 'id': id, 'account': account}})

class Register(APIView):
    def post(self, request):
        code = request.data.get("code")
        account = request.data.get('account')
        password = request.data.get('password')
        rediscode = redistoll.get_str(account)
        data = {}
        if re.match(r'^1[3-9]\d{9}$', account) and code is None:
            return Response({"code": 400, "msg": "请输入验证码"})
        if re.match(r"^1[3-9]\d{9}$", account) and code != rediscode:
            return Response({"code": 400, "msg": "验证码错误"})

        if re.match(r'^1[3-9]\d{9}$', account):
            data['phone'] = account
        elif re.match(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', account):
            data['email'] = account
        else:
            data['username'] = account
        data['password'] = password
        ser = userser.UserSerializer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '注册成功', 'data': ser.data})
        return Response({'code': 400, 'msg': '注册失败', 'data': ser.errors})

class CheckPhone(APIView):
    def get(self, request):
        phone = request.GET.get('phone')
        info = UserModel.objects.filter(phone=phone).first()
        if info:
            return Response({'code': 400, 'msg': '手机号已存在'})
        return Response({'code': 200, "msg": '手机号可用'})

class TestUser(APIView):
    def post(self,request):
        sum_=add.delay(1,2)
        print(sum_.get())
        return Response({'code':200,'msg':'测试成功'})

class Cart(APIView):
    authentication_classes = [MyAuthentication]
    def get(self,request):
        return Response({'code':200,'msg':'购物车'})
